import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import {
  Form, Input, Button, Table, Tag, Space, Popconfirm,
  Modal,
  message
} from 'antd';
import { UndoOutlined, PlusOutlined } from '@ant-design/icons';
import { getEstateList, updateEstate, createEstate, delEstate } from '@/services/ant-design-pro/api';
import _ from 'lodash';
import moment from 'moment';
import styles from './index.less';
import { useRef } from 'react';

import { Link, history } from 'umi';


export default (): React.ReactNode => {
  const [form] = Form.useForm();
  const [, forceUpdate] = useState({});
  const [estate, setEstate] = useState([]);
  const [pagination, setPagination] = useState({ current: 1, page_size: 10, total: 0 });
  const [listLoading, setListLoading] = useState(false);
  const [searchVal, setSearchVal] = useState('TEST');
  const [createEstateModal, setCreateEstateModal] = useState(false)
  const estateNameInput = useRef<Input>(null);
  /**
   * 获取楼盘列表
   */
  const queryEstateList = async (params: any) => {
    try {
      setListLoading(true);

      const resp = await getEstateList({ params: { ...params } });

      const list = _.get(resp, 'data.list', []);
      const page = _.get(resp, 'data.pagination', {});
      console.log(resp)
      setEstate(list);
      setPagination(page);
      setListLoading(false);
    } catch (err) {
      setListLoading(false);
      throw new Error(err);
    }
  };

  useEffect(() => forceUpdate({}), []);

  useEffect(() => {
    queryEstateList(pagination);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const onFinish = (values: { text: string }) => {
    console.log('finish', values);
  };

  /**
   * 搜索框
   */
  const handleSearch = () => {
    const params = { estate_name: searchVal, current: 1, page_size: 10 };
    queryEstateList(params);
  };

  /**
   * 分页
   */
  const handlePageChange = (page: number, page_size?: number | undefined) => {
    const params = { current: page, page_size };
    queryEstateList(params);
  };

  /**
   * 重置搜索
   */
  const handleResetSearch = () => {
    const params = { current: 1, page_size: 10 };
    queryEstateList(params);
  };

  /**
   * 修改楼盘状态
   */
  const handleChangeStatus = async (id: number, in_store: number) => {
    const params = { id, data: { in_store } }
    await updateEstate(params)
    const queryListParams = { current: pagination.current, page_size: pagination.page_size }
    await queryEstateList(queryListParams)
  }

  /**
   * 确认新增楼盘
   */
  const handleConfirmCreateEstate = async () => {
    if (estateNameInput && estateNameInput.current) {
      const val = estateNameInput.current.state.value;
      if (val) {
        const res = await createEstate({ data: { estate_name: val } })
        const id = _.get(res, "data.insertId", false)
        if (id) {
          history.push(`/base-data/community-detail/${id}`);
        } else {
          message.error("创建楼盘失败，请重试。")
        }
      }
    }

  }

  /**
   * 删除楼盘
   */
  const handleDelEstate = async (id: number) => {
    await delEstate({ id })
    await queryEstateList(pagination);
  }

  /**
   * table字段
   */
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: '名称',
      dataIndex: 'estate_name',
    },
    {
      title: '区域',
      dataIndex: 'district',
    },
    {
      title: '参考总价',
      dataIndex: 'total_price',
    },
    {
      title: '参考均价',
      dataIndex: 'average_price',
    },
    {
      title: '上架状态',
      dataIndex: 'in_store',
      render: (in_store: number) => {
        let color = 'volcano';
        if (in_store) {
          color = 'green';
        }
        return <Tag color={color}>{in_store ? '展示中' : '已下架'}</Tag>;
      },
    },
    {
      title: '排序',
      dataIndex: 'order',
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      title: '编辑时间',
      dataIndex: 'm_time',
      render: (time: string) => <Space>{moment(time).format('YYYY-MM-DD HH:mm:ss')}</Space>,
    },
    {
      title: '编辑',
      render: (text: string, record: { name: string; in_store: number, id: number }) => (
        <Space>
          <Link to={`/base-data/community-detail/${record.id}`}> 编辑</Link>

          <Popconfirm
            title={`确认${record.in_store ? '下架' : '上架'}?`}
            onConfirm={() => { handleChangeStatus(record.id, record.in_store === 1 ? 0 : 1) }}
            okText="确认"
            cancelText="取消"
          >
            <Button type="link" danger={!!record.in_store}>
              {record.in_store ? '下架' : '上架'}
            </Button>
          </Popconfirm>

          <Popconfirm
            title={`确认删除?`}
            onConfirm={() => handleDelEstate(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>

        </Space>
      ),
    },
  ];
  return (
    <PageContainer>
      <div className={styles.search_content}>
        <Form form={form} name="search" layout="inline" onFinish={onFinish}>
          <Form.Item name="text" label="搜索：">
            <Input
              placeholder="请输入楼盘名称"
              value={searchVal}
              onChange={(e: React.FormEvent<HTMLInputElement>) => {
                setSearchVal(e.currentTarget.value);
              }}
            />
          </Form.Item>
          <Form.Item shouldUpdate>
            <Button type="primary" onClick={handleSearch}>
              {' '}
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button icon={<UndoOutlined />} onClick={handleResetSearch}>
              {' '}
              重置{' '}
            </Button>
          </Form.Item>
          <Form.Item>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateEstateModal(true)}>
              {' '}
              新建楼盘
            </Button>
          </Form.Item>
        </Form>
      </div>
      {/* 新增楼盘modal */}
      <Modal
        title="新建楼盘"
        visible={createEstateModal}
        onOk={handleConfirmCreateEstate}
        onCancel={() => setCreateEstateModal(false)}
      >
        <Input ref={estateNameInput} placeholder="请输入楼盘名称" />
      </Modal>
      <div className={styles.search_content}>
        <Table
          columns={columns}
          dataSource={estate}
          pagination={{
            current: pagination.current,
            pageSize: pagination.page_size,
            total: pagination.total,
            onChange: handlePageChange,
          }}
          loading={listLoading}
          rowKey="id"
        />
      </div>
    </PageContainer>
  );
};
